use crate::db::dao::candidate_path::CandidatePathDao;
use crate::db::{dao, po};
use crate::dto;
use crate::service::Error;
use std::sync::Arc;
use wanmesh_common::error::ResponseError;

#[async_trait::async_trait]
pub trait CandidatePathService: Sync + Send {
    async fn add(
        &self,
        params: &dto::core::candidate_path::AddParams,
    ) -> Result<dto::core::candidate_path::AddResponseData, Error>;

    async fn get(
        &self,
        candidate_path_id: &str,
    ) -> Result<dto::core::candidate_path::CandidatePathItem, Error>;

    async fn try_get(
        &self,
        candidate_path_id: &str,
    ) -> Result<Option<dto::core::candidate_path::CandidatePathItem>, Error>;

    async fn list(
        &self,
        filter: &dto::core::candidate_path::Filter,
        offset: u64,
        limit: u64,
    ) -> Result<Vec<dto::core::candidate_path::CandidatePathItem>, Error>;

    async fn update(
        &self,
        candidate_path_id: &str,
        params: &dto::core::candidate_path::UpdateParams,
    ) -> Result<(), Error>;

    async fn delete(&self, candidate_path_id: &str) -> Result<(), Error>;

    async fn delete_by_filter(
        &self,
        filter: &dto::core::candidate_path::Filter,
    ) -> Result<(), Error>;

    async fn count(&self, filter: &dto::core::candidate_path::Filter) -> Result<u64, Error>;
}

pub struct DefaultCandidatePathService {
    candidate_path_dao: Arc<dyn CandidatePathDao>,
}

impl DefaultCandidatePathService {
    pub fn new(candidate_path_dao: Arc<dyn CandidatePathDao>) -> Self {
        Self { candidate_path_dao }
    }
}

#[async_trait::async_trait]
impl CandidatePathService for DefaultCandidatePathService {
    async fn add(
        &self,
        params: &dto::core::candidate_path::AddParams,
    ) -> Result<dto::core::candidate_path::AddResponseData, Error> {
        let candidate_path_id = wanmesh_common::util::new_id()?;

        self.candidate_path_dao
            .insert(po::candidate_path::ActiveModel {
                id: Default::default(),
                candidate_path_id: po::ActiveValue::Set(candidate_path_id.clone()),
                te_policy_group_id: po::ActiveValue::Set(params.te_policy_group_id.clone()),
                name: po::ActiveValue::Set(params.name.clone()),
                description: po::ActiveValue::Set(params.description.clone()),
                preference: po::ActiveValue::Set(params.preference),
                create_timestamp_millis: Default::default(),
                update_timestamp_millis: Default::default(),
            })
            .await?;

        Ok(dto::core::candidate_path::AddResponseData { candidate_path_id })
    }

    async fn get(
        &self,
        candidate_path_id: &str,
    ) -> Result<dto::core::candidate_path::CandidatePathItem, Error> {
        let candidate_path = self
            .try_get(candidate_path_id)
            .await?
            .ok_or(ResponseError::candidate_path_not_found(candidate_path_id))?;
        Ok(candidate_path)
    }

    async fn try_get(
        &self,
        candidate_path_id: &str,
    ) -> Result<Option<dto::core::candidate_path::CandidatePathItem>, Error> {
        let filter = dao::candidate_path::Filter {
            candidate_path_id: Some(candidate_path_id.to_string()),
            ..Default::default()
        };

        if let Some(m) = self.candidate_path_dao.try_get(filter).await? {
            return Ok(Some(m.into()));
        }

        Ok(None)
    }

    async fn list(
        &self,
        filter: &dto::core::candidate_path::Filter,
        offset: u64,
        limit: u64,
    ) -> Result<Vec<dto::core::candidate_path::CandidatePathItem>, Error> {
        let po_list = self
            .candidate_path_dao
            .find(dao::FindParams {
                filter: filter.into(),
                offset: Some(offset),
                limit: Some(limit),
                ..Default::default()
            })
            .await?;

        let list = po_list.into_iter().map(|m| m.into()).collect();

        Ok(list)
    }

    async fn update(
        &self,
        candidate_path_id: &str,
        params: &dto::core::candidate_path::UpdateParams,
    ) -> Result<(), Error> {
        if params == &Default::default() {
            return Ok(());
        }

        let filter = dao::candidate_path::Filter {
            candidate_path_id: Some(candidate_path_id.to_string()),
            ..Default::default()
        };

        self.candidate_path_dao
            .update(filter, params.into())
            .await?;

        Ok(())
    }

    async fn delete(&self, candidate_path_id: &str) -> Result<(), Error> {
        let filter = dao::candidate_path::Filter {
            candidate_path_id: Some(candidate_path_id.to_string()),
            ..Default::default()
        };
        self.candidate_path_dao.delete(filter.into()).await?;
        Ok(())
    }

    async fn delete_by_filter(
        &self,
        filter: &dto::core::candidate_path::Filter,
    ) -> Result<(), Error> {
        self.candidate_path_dao.delete(filter.into()).await?;
        Ok(())
    }

    async fn count(&self, filter: &dto::core::candidate_path::Filter) -> Result<u64, Error> {
        let count = self.candidate_path_dao.count(filter.into()).await?;
        Ok(count)
    }
}

impl From<&dto::core::candidate_path::Filter> for dao::candidate_path::Filter {
    fn from(value: &dto::core::candidate_path::Filter) -> Self {
        Self {
            candidate_path_id: None,
            te_policy_group_id: value.te_policy_group_id.clone(),
            name: value.name.clone(),
        }
    }
}

impl From<dto::core::candidate_path::Filter> for dao::candidate_path::Filter {
    fn from(value: dto::core::candidate_path::Filter) -> Self {
        Self::from(&value)
    }
}

impl From<&dto::core::candidate_path::UpdateParams> for dao::candidate_path::UpdateParams {
    fn from(value: &dto::core::candidate_path::UpdateParams) -> Self {
        Self {
            name: po::option_to_active_value(value.name.clone()),
            description: po::option_to_active_value(value.description.clone()),
            preference: po::option_to_active_value(value.preference),
        }
    }
}

impl From<dto::core::candidate_path::UpdateParams> for dao::candidate_path::UpdateParams {
    fn from(value: dto::core::candidate_path::UpdateParams) -> Self {
        Self::from(&value)
    }
}

impl From<&po::candidate_path::Model> for dto::core::candidate_path::CandidatePathItem {
    fn from(value: &po::candidate_path::Model) -> Self {
        Self {
            candidate_path_id: value.candidate_path_id.clone(),
            inner: dto::core::candidate_path::CandidatePath {
                te_policy_group_id: value.te_policy_group_id.clone(),
                name: value.name.clone(),
                description: value.description.clone(),
                preference: value.preference,
            },
        }
    }
}

impl From<po::candidate_path::Model> for dto::core::candidate_path::CandidatePathItem {
    fn from(value: po::candidate_path::Model) -> Self {
        Self::from(&value)
    }
}
